//index.js
//获取应用实例
import {
  ajax,
  src,
  util
} from "../../utils/util.js";

const app = getApp()

var top = app.globalData.navTop
var height = app.globalData.navHeight
console.log(app.globalData)
let isIphoneX = app.globalData.isIphoneX;



Page({
  data: {
    userInfo: "",
    islogin: "",
    include_points: "",
    isiphone: isIphoneX,
    isPhoneAuth: 0,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    latitude: '',
    longitude: '',
    navHeight: height,
    current: 0,
    pet_list: "",
    navData: [{
      name: "找舱舱", //文本
      index: 0, //是否是当前页，0不是  1是
      style: 0, //样式
      ico: 'faxian', //不同图标
      fn: 'gotoIndex' //对应处理函数
    }, {
      name: "",
      index: "",
      style: 1,
      ico: '',
      fn: 'gotoScan',
    }, {
      name: "我的",
      index: 1,
      style: 0,
      ico: 'wode',
      fn: 'gotoMine'
    }, ],
    haveorder: 0,
    orderid: "",
    kftel: "",
    showaddresstc: false,
    orderstatus: "",
    messs: "",
    // mobanid:""
  },
  // userInfo: {},
  // hasUserInfo: false,
  // canIUse: wx.canIUse('button.open-type.getUserInfo'),


  // authMsg(event) {

  //   wx.requestSubscribeMessage({
  //     tmplIds: this.data.mobanid,
  //     success: function(res) {
  //       console.log(res)
  //     },
  //     fail: function(err) {
  //       console.log(err)
  //     }
  //   })
  // },

  // getmobanid:function(){
  //   ajax('/api/scan/get_template', {
  //     data: {
      
  //     },
  //     header: {
  //       'Accept': 'application/json', // 默认值
  //     },
  //     method: 'get'
  //   }, res => { 
  //     this.setData({
  //       mobanid:res.data
  //     })
  //   })
  // },

  onShow: function() {
    wx.getSetting({
      success(res) {
        console.log(res)
      }
    })


    this.setData({
      showaddresstc: false
    })
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy

        wx.setStorageSync("latitude", latitude)
        wx.setStorageSync("longitude", longitude)

        // console.log(latitude)
      },
      fail: (res) => {
        this.setData({
          showaddresstc: true
        })
      },
    })

    var uqid = wx.getStorageSync('uqid');
    var tel = wx.getStorageSync('uqid');
    if (uqid == '' || tel == '') {
      this.setData({
        islogin: 0
      });
    } else {
      this.setData({
        uqid: uqid
      })
      this.getInfofirst(uqid);
      this.checkorder(uqid);
    }

    var that = this
    var timer = setInterval(function() {
      var aa = that
      var latitude = wx.getStorageSync('latitude')
      var longitude = wx.getStorageSync('longitude')
      console.log("11")
      if (latitude) {
        console.log(latitude)
        aa.setData({
          latitude: latitude,
          longitude: longitude
        });
        clearInterval(timer)
        that.getpetlist(latitude, longitude)

      }
    }, 100)
  },


  
  phoneCall: function(e) {
    var tel = e.currentTarget.dataset.tel;

    if (wx.getStorageSync("uqid")){
      ajax("/api/user/service", {
        data: {
          uqid: this.data.uqid,
        },
        header: {
          'Accept': 'application/json', // 默认值
        },
        method: 'get'
      }, res => {
        console.log(res);
        if (res.error == 0) {
          this.setData({
            kftel: res.data.admin_phone
          })
          wx.makePhoneCall({
            phoneNumber: res.data.admin_phone //仅为示例，并非真实的电话号码
          })
        }
      })
    }else{
      wx.showToast({
        title: '请先授权！',
        icon: 'none',
        duration: 2000
      })

    }
    
  },

  userSubmit: function(e) {
    if (this.data.uqid) {
      console.log(e.detail.formId);
      ajax('/api/user/form_id', {
        data: {
          uqid: this.data.uqid,
          form_id: e.detail.formId
        },
        header: {
          'Accept': 'application/json', // 默认值
        },
        method: 'post'
      }, res => {})
    }
  },

  //事件处理函数
  onLoad: function() {




    var uqid = wx.getStorageSync('uqid');
    this.setData({
      uqid: uqid
    })
    if (uqid == '') {
      this.setData({
        islogin: 0
      });
    } else {
      this.getInfofirst(uqid);
      this.checkorder(uqid);
    }

    var that = this
    var timer = setInterval(function() {
      var aa = that
      var latitude = wx.getStorageSync('latitude')
      var longitude = wx.getStorageSync('longitude')
      console.log("11")
      if (latitude) {
        console.log(latitude)
        aa.setData({
          latitude: latitude,
          longitude: longitude
        });
        clearInterval(timer)
        that.getpetlist(latitude, longitude)
      }
    }, 100)

  },

  checkorder: function(uqid) {
    ajax('/api/index/undone_order', {
      data: {
        uqid: uqid
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'get'
    }, res => {
      console.log(res)
      if (res.error == 0) {
        this.setData({
          haveorder: 1,
          orderid: res.data.order_id
        })

        if (res.data.code == 1) {
          this.setData({
            messs: "您有正在进行的的订单",
            orderstatus: res.data.code
          })
        }
        if (res.data.code == 2) {
          this.setData({
            messs: "您有未支付的的订单",
            orderstatus: res.data.code
          })
        }

      } else if (res.error == 4027) {
        this.setData({
          haveorder: 0
        })
      }
    })
  },

  tojishiye: function() {

    if (this.data.orderstatus == 1) {
      wx.navigateTo({
        url: '/pages/storaging/storaging?orderid=' + this.data.orderid,
      })
    }

    if (this.data.orderstatus == 2) {
      wx.navigateTo({
        url: '/pages/topay/topay?orderid=' + this.data.orderid,
      })
    }


  },

  gotoScan: function(e) {

    if (this.data.islogin) {
      this.tonext()
    } else {
      var that = this
      if (e.detail.userInfo) {
        //用户按了允许授权按钮
        var code = wx.getStorageSync("code");
        ajax('/api/user/login', {
          data: {
            code: code,
            nickname: e.detail.userInfo.nickName,
            avatar: e.detail.userInfo.avatarUrl
          },
          header: {
            'Accept': 'application/json', // 默认值
          },
          method: 'post'
        }, res => {
          console.log(res)
          if (res.error == 0) {
            wx.setStorageSync("uqid", res.data.uqid)

            that.setData({
              uqid: res.data.uqid,
              session_key: res.data.session_key,
            });
            that.getInfo(res.data.uqid)
            that.getkefutel()
          } else if (res.error == 4003) { //重复授权
            that.getInfo(this.data.uqid)
            that.getkefutel()
          }
        })
      } else {
        wx.showToast({
          title: '请先授权！',
          icon: 'none',
          duration: 2000
        })

      }
    }
  },

  isPhone: function() {
    var that = this;
    var tel = wx.getStorageSync("tel");
    console.log(tel)
    if (tel == undefined || tel == '') { //用户没有授权手机号
      that.setData({
        isPhoneAuth: 1
      });

    } else { //用户已经授权手机号
      that.setData({
        isPhoneAuth: 0
      });
      that.tonext()
    }
  },

  useotherphone: function() {

    this.setData({
      isPhoneAuth: 0
    })

    wx.navigateTo({
      url: '/pages/bindphone/bindphone',
    })
  },

  tonext: function() {
    var isfirst = this.data.userInfo.is_prompt
    if (isfirst == 1) {
      wx.navigateTo({
        url: '/pages/procedure/procedure',
      })
    } else {
      var _this = this;

      wx.scanCode({
        success: (res) => {
          var result = res.result;
          _this.setData({
            did: result,
          })

          wx.navigateTo({
            url: '/pages/unlocking/unlocking?did=' + this.data.did,
          })
        }
      })
      // wx.navigateTo({
      //   url: '/pages/unlocking/unlocking?numbering=' +"001",
      // })
    }
  },

  //同意授权手机号
  getPhoneNumber(e) {
    this.setData({
      isPhoneAuth: 0
    })
    console.log(e)

    if (e.detail.encryptedData) {
      ajax("/api/user/decrypt_data", {
        data: {
          uqid: this.data.uqid,
          session_key: this.data.session_key,
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData
        },
        header: {
          'Accept': 'application/json', // 默认值
        },
        method: 'GET'
      }, res => {

        // console.log(res);
        // console.log(1111111111111111111111111111111);

        if (res.error == 0) {
          var tel = res.data.phoneNumber;
          wx.setStorageSync("tel", tel)
        }
        this.tonext()
      })
    }
  },
  //拒绝授权手机号
  refuseUserInfo: function() {
    this.setData({
      isPhoneAuth: 0
    });
    this.tonext()
  },

  getpetlist: function(latitude, longitude) {
    ajax("/api/index/pet_list", {
      data: {
        latitude: longitude,
        longitude: latitude
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'GET'
    }, res => {
      console.log(res);

      if (res.error == 0) {
        var pet_list = []

        for (var key in res.data) {
          var obj = res.data[key]
          // console.log(obj)
          // console.log(key)
          //使用状态(0 - 未使用 1 - 消毒中  2 - 在使用 3 - 维护中)
          obj.width = 27
          obj.height = 54
          if (obj.use_status == 0) {
            obj.iconPath = "../images/kx.png"
          }
          if (obj.use_status == 2) {
            obj.iconPath = "../images/syz.png"
          }
          if (obj.use_status == 1 || obj.use_status == 3) {
            obj.iconPath = "../images/xdz.png"
          }
          // console.log(obj)
          pet_list.push(obj)
        }
        this.setData({
          pet_list: pet_list
        })
        var include_points = [].concat(pet_list)
        include_points.push({
          latitude: this.data.latitude,
          longitude: this.data.longitude
        })
        this.setData({
          include_points: include_points
        })
      }
    })
  },

  tosearchpage: function() {

    if (this.data.islogin) {
      wx.navigateTo({
        url: '/pages/searchpage/searchpage',
      })
    } else {
      if (wx.getStorageSync('uqid')!=""){
        wx.showToast({
          title: '请先绑定手机号',
          icon: 'none',
          duration: 2000
        })
     }else{
       wx.showToast({
         title: '请先登录授权！',
         icon: 'none',
         duration: 2000
       })
     }
    }
  },



  getInfo: function(uqid) {
    console.log(uqid)
    ajax("/api/user/user_info", {
      data: {
        uqid: uqid,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      console.log(res);
      if (res.error == 0) {
        console.log("set 1 次")
        this.setData({
          userInfo: res.data,
        });

        if (res.data.phone) {
          this.setData({
            tel: res.data.phone
          });
          wx.setStorageSync("tel", res.data.phone)
          this.setData({
            islogin: 1,
          });
        }
        this.isPhone()
      }
    })
  },

  getInfofirst: function(uqid) {
    console.log(uqid)
    ajax("/api/user/user_info", {
      data: {
        uqid: uqid,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      console.log(res);
      if (res.error == 0) {
        console.log("set 1 次")
        this.setData({
          userInfo: res.data,

        });
        if (res.data.phone) {
          this.setData({
            tel: res.data.phone
          });
          wx.setStorageSync("tel", res.data.phone)
          this.setData({
            islogin: 1
          });
        }

      }
    })
  },



  markertap: function(e) {

    if (this.data.islogin) {
      console.log(e.markerId)
      wx.navigateTo({
        url: '/pages/cabinet/cabinet?markerId=' + e.markerId,
      })
    } else {
      if (wx.getStorageSync('uqid') != "") {
        wx.showToast({
          title: '请先绑定手机号',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '请先登录授权！',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },

  gotoIndex: function() {
    wx.reLaunch({
      url: '/pages/index/index',
    })
    this.setData({
      current: 0
    });
  },
  gotoMine: function() {
    wx.reLaunch({
      url: '/pages/mine/mine',
    })
    this.setData({
      current: 1
    });
  },
  getjifen:function(){
    ajax("/api/index/forward_send", {
      data: {
        uqid: this.data.uqid,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'post'
    }, res => {
      console.log(res);
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    this.getjifen();
  }

})